package com.dg.river.module.login.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.dg.river.R;
import com.dg.river.core.http.ApiManager;
import com.dg.river.core.manager.UserInfoManager;
import com.dg.river.core.manager.UserInfoMethod;
import com.dg.river.core.util.EmojiFilterUtils;
import com.dg.river.core.util.TextUtil;
import com.dg.river.core.util.ToastUtils;
import com.dg.river.core.util.Utils;
import com.dg.river.databinding.ActivityLoginBinding;
import com.dg.river.module.base.BaseActivity;
import com.dg.river.module.web.WebLinkActivity;
import com.gyf.immersionbar.ImmersionBar;

/**
 * @作者：HuYong
 * @时间：2023/4/12 16:19
 * @描述：登录
 * @xml：activity_login.xml
 * @修改：
 */
public class LoginActivity extends BaseActivity {

    private ActivityLoginBinding binding;
    private String phoneNum, password;
    private String toastMsg = "";
    private int checkCount = 0;

    public static final String TOAST_MSG = "toastMsg";

    public static void start(Context mContext) {
        Intent intent = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(intent);
    }

    public static void startTop(Context mContext, String toastMsg) {
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra(TOAST_MSG, toastMsg);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    @NonNull
    @Override
    public View initLayout() {
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initGetIntent() {
        super.initGetIntent();
        toastMsg = getIntent().getStringExtra(TOAST_MSG);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            toastMsg = intent.getStringExtra(TOAST_MSG);
        }
    }

    @Override
    public void initView() {
        //navigationBar:导航栏颜色，不写默认是黑色 statusBar:状态栏的颜色，不写默认透明
        ImmersionBar.with(this)
                .navigationBarColor(R.color.transparent)
                .autoDarkModeEnable(true, 0.2f)
                .statusBarDarkFont(true)
                .keyboardEnable(false).init();

        // 显示用户协议
        String message = "请您阅读并同意《用户协议》《隐私政策》";
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(message);
        spannableStringBuilder.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                WebLinkActivity.start(mContext, ApiManager.Web.USER_URL, "用户协议");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(mContext, R.color.blue_0070f9));
                ds.setUnderlineText(false);//设置下划线
            }
        }, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                WebLinkActivity.start(mContext, ApiManager.Web.PRIVATE_URL, "隐私政策");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(mContext, R.color.blue_0070f9));
                ds.setUnderlineText(false);//设置下划线
            }
        }, 13, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        binding.tvAgreement.setText(spannableStringBuilder);
        binding.tvAgreement.setHighlightColor(ContextCompat.getColor(mContext, R.color.white));
        binding.tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());

        // 记住账号密码填充
        binding.edUsername.setText(TextUtil.isEmptyConvert(UserInfoManager.getInstance().rememberAccount(UserInfoMethod.GET, "")));
        if (UserInfoManager.getInstance().rememberPasswordChangeDefault(UserInfoMethod.GET, false)) {
            if (!TextUtil.isEmpty(UserInfoManager.getInstance().rememberPassword(UserInfoMethod.GET, ""))) {
                binding.edPassword.setText(TextUtil.isEmptyConvert(UserInfoManager.getInstance().rememberPassword(UserInfoMethod.GET, "")));
                binding.checkBoxRememberPassword.setChecked(true);
            } else {
                binding.edPassword.setText("");
                binding.checkBoxRememberPassword.setChecked(false);
            }
        } else {
            binding.edPassword.setText("");
            binding.checkBoxRememberPassword.setChecked(true);
        }

        // 提示Msg信息
        if (!TextUtil.isEmpty(toastMsg)) {
            ToastUtils.getInstance().toast(toastMsg);
        }
    }

    @Override
    public boolean viewAndData() {
        return true;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {
        binding.tvLogin.setOnClickListener(v -> {
            binding.tvLogin.setEnabled(false);
            if (EmojiFilterUtils.hasEmoji(binding.edUsername.getText().toString().trim())) {
                ToastUtils.getInstance().toast("请不要输入表情符号");
                binding.tvLogin.setEnabled(true);
                return;
            }
            if (EmojiFilterUtils.hasEmoji(binding.edPassword.getText().toString().trim())) {
                ToastUtils.getInstance().toast("请不要输入表情符号");
                binding.tvLogin.setEnabled(true);
                return;
            }
            phoneNum = binding.edUsername.getText().toString();
            password = binding.edPassword.getText().toString();
            if (TextUtil.isEmpty(phoneNum)) {
                ToastUtils.getInstance().toast("请输入登录账号");
                binding.tvLogin.setEnabled(true);
                return;
            }
            if (TextUtil.isEmpty(password)) {
                ToastUtils.getInstance().toast("请输入密码");
                binding.tvLogin.setEnabled(true);
                return;
            }
            if (!binding.cbAgree.isChecked()) {
                Utils.doShake(mContext, binding.llAgreement);
                binding.tvLogin.setEnabled(true);
                return;
            }
            login();
        });
        binding.tvForgotPassWord.setOnClickListener(v -> {
            ForgotPasswordActivity.start(mContext, true);
        });
        binding.edUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtil.isEmpty(s.toString())) {
                    binding.edUsername.getPaint().setFakeBoldText(true);
                } else {
                    binding.edUsername.getPaint().setFakeBoldText(false);
                }
            }
        });
        binding.edUsername.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    binding.viewUserName.setBackgroundColor(ContextCompat.getColor(mContext, R.color.blue_92CEFF));
                } else {
                    binding.viewUserName.setBackgroundColor(ContextCompat.getColor(mContext, R.color.gray_ebf1f4));
                }
            }
        });
        binding.edPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtil.isEmpty(s.toString())) {
                    binding.edPassword.getPaint().setFakeBoldText(true);
                } else {
                    binding.edPassword.getPaint().setFakeBoldText(false);
                }
            }
        });
        binding.edPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    binding.viewPassWord.setBackgroundColor(ContextCompat.getColor(mContext, R.color.blue_92CEFF));
                } else {
                    binding.viewPassWord.setBackgroundColor(ContextCompat.getColor(mContext, R.color.gray_ebf1f4));
                }
            }
        });
        binding.checkBoxRememberPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                UserInfoManager.getInstance().rememberPasswordChangeDefault(UserInfoMethod.SET, true);
            }
        });
    }

    /**
     * 登录
     */
    private void login() {

    }

    @Override
    public void showErrorMessage(@Nullable String message) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Utils.clickToExit(mContext);
        }
        return false;
    }
}
